// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, Picker, InteractionManager } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Ionicons';
import * as ActionTypes from '../../constants/constants.js'

// antd 按需加载
import { Tabs, Toast } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { checkOrders, addPurchase, promptlyConfirmOrder } from './module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, RnImage } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { press, size, ScreenWidth } from '../../util/utils.js'


class SubmitOrders extends Component {
  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
      delivery: 1,
      orderShipping: {
        fee: 0,
        totalAmount: this.getPrice()
      }
    }
    this.checkOrders = checkOrders.bind(this)
    this.addPurchase = addPurchase.bind(this)
    this.promptlyConfirmOrder = promptlyConfirmOrder.bind(this)
  }

  componentDidMount() {
    // InteractionManager.runAfterInteractions(() => {
    // ...耗时较长的同步执行的任务...
    // });
    const { dispatch, confirmOrder, selectAddress, defaultAddress, goodsList, price, submitType } = this.props
    const { delivery } = this.state
    if (submitType == 'buy') {
      // 一键购买生成确认单信息
      this.promptlyConfirmOrder({
        carryWay: delivery,
        memberReceiveAddressId: selectAddress ? selectAddress.id : defaultAddress.id,
        orderType: 4,
        payType: 3,
        productId: goodsList[0].id,
        productQuantity: 1,
        sourceType: 1
      }).then(res => {
        console.log(res)
        this.checkOrders({
          disModes: this.state.delivery,
          addrId: this.props.selectAddress.id
        }).then(res => {
          this.setState({
            orderShipping: res.data.data
          })
        })
      })
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.selectAddress != nextProps.selectAddress.id) {
      this.checkOrders({
        disModes: this.state.delivery,
        addrId: nextProps.selectAddress.id
      }).then(res => {
        this.setState({
          orderShipping: res.data.data
        })
      })
    }
  }



  getPrice() {
    const { submitType, price, confirmOrder } = this.props
    if (this.isSubmitType()) {
      return price
    } else {
      return confirmOrder.calcAmount.totalAmount
    }
  }

  renderDefaultAddress() {
    const { selectAddress, defaultAddress } = this.props
    // 如果存在默认地址，显示默认地址，如果存在用户选择的地址，显示用户选择的地址
    let address
    if (defaultAddress) {
      address = defaultAddress
    }
    if (selectAddress) {
      address = selectAddress
    }
    if (address) {
      return (
        <TouchableOpacity
          onPress={() => Actions.address({ select: true })}
          style={{
            padding: 15,
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: '#fff',
            marginBottom: 10,
            borderRadius: 6,
          }}>
          <Icon name={'md-pin'} size={22} color={'#666'} />
          <View style={{
            marginLeft: 10
          }}>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>收件人：{address.name}</Text>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 30 }}>{address.phoneNumber}</Text>
            </View>
            <View style={{
              flexDirection: 'row',
            }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>收货地址：</Text>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, flex: 1 }} numberOfLines={10} >{address.countryCn} {address.stateCn} {address.detailAddress}</Text>
            </View>
          </View>
        </TouchableOpacity>
      )
    } else {
      return (
        <TouchableOpacity
          onPress={() => Actions.address({ select: true })}
        >
          <View style={{
            padding: 15,
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: '#fff',
            justifyContent: 'center',
          }}>
            <Icon name={'md-add'} size={22} color={'#666'} />
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 10 }}>选择收货地址</Text>
          </View>
        </TouchableOpacity>
      )
    }
  }

  getQuantity() {
    const { confirmOrder } = this.props
    let quantity = 0
    confirmOrder.cartPromotionItemList.map((item, index) => {
      quantity += item.quantity
    })
    return quantity
  }

  renderDelivery() {
    const { confirmOrder } = this.props
    const { delivery, orderShipping } = this.state
    if (delivery == 1) {
      return (
        <View style={{
          backgroundColor: '#fff',
          marginBottom: 10,
          borderRadius: 6,
          paddingVertical: 8,
        }}>
          <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>自提</Text>
            <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>0.00</Text>
          </View>
          {/* <View style={{ paddingHorizontal: 15, marginBottom: 5 }}>
            <Text style={{ fontSize: 12, color: '#a1aab8', lineHeight: 16, textAlign: 'right' }}>以后台审核实际运费为准</Text>
          </View> */}
        </View>
      )
    }
    if (delivery == 2) {
      return (
        <View style={{
          backgroundColor: '#fff',
          marginBottom: 10,
          borderRadius: 6,
          paddingVertical: 8,
        }}>
          <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>大马本地特快费用</Text>
            <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>{orderShipping.fee}</Text>
          </View>
          {/* <View style={{ paddingHorizontal: 15, marginBottom: 5 }}>
            <Text style={{ fontSize: 12, color: '#a1aab8', lineHeight: 16, textAlign: 'right' }}>以后台审核实际运费为准</Text>
          </View> */}
        </View>
      )
    }

  }

  /**
   * * 判断当前订单状态 
   * * @true 为 立即购买/预约  @false 为 下单
   * @returns
   * @memberof SubmitOrders
   */
  isSubmitType() {
    const { submitType } = this.props
    console.log(submitType)
    return submitType && submitType == 'buy' || submitType && submitType == 'reservation'
  }

  handleToPay() {
    const { dispatch, confirmOrder, selectAddress, defaultAddress, goodsList, price, submitType } = this.props
    const { delivery, orderShipping } = this.state
    if (!selectAddress && !defaultAddress) {
      Toast.fail('请选择收货地址', 1, null, false)
      return
    }
    let order = {
      goodsList: [],
      disModes: delivery,
      memberReceiveAddressId: selectAddress ? selectAddress.id : defaultAddress.id,
      payType: null
    }
    if (this.isSubmitType()) {
      // 立即购买或预定
      order.goodsList = [{
        acid: goodsList[0].acid,// integer($int64) allowEmptyValue: false 活动Id 当产品类型为 1每日特价 时此参数 必须
        checked: 1,// integer($int32) allowEmptyValue: false 是否选择该物品结算
        pid: goodsList[0].id,// integer($int64) allowEmptyValue: false 产品id
        ptype: goodsList[0].ptype || null,// integer($int32) allowEmptyValue: false 产品类型 1每日特价 2新品上市 3推荐商品 4杂志代购
        quantity: goodsList[0].quantity || null,// integer($int32) allowEmptyValue: false 物品数量
        skuId: goodsList[0].productSkuId || null,// integer($int64) allowEmptyValue: false skuId
      }]
    } else {
      // 下单
      order.goodsList = confirmOrder.cartPromotionItemList.map(item => {
        return {
          acid: item.acid,// integer($int64) allowEmptyValue: false 活动Id 当产品类型为 1每日特价 时此参数 必须
          checked: item.checked,// integer($int32) allowEmptyValue: false 是否选择该物品结算
          pid: item.productId,// integer($int64) allowEmptyValue: false 产品id
          ptype: item.ptype,// integer($int32) allowEmptyValue: false 产品类型 1每日特价 2新品上市 3推荐商品 4杂志代购
          quantity: item.quantity,// integer($int32) allowEmptyValue: false 物品数量
          skuId: item.productSkuId,// integer($int64) allowEmptyValue: false skuId
        }
      })
    }

    if (submitType && submitType == 'reservation') {
      // 预定
      this.addPurchase({
        carryWay: delivery,
        memberReceiveAddressId: selectAddress ? selectAddress.id : defaultAddress.id,
        orderType: 4,
        payType: 3,
        productId: goodsList[0].id,
        productQuantity: 1,
        sourceType: 1
      })
    } else if (submitType && submitType == 'buy') {
      // 立即购买
      // this.promptlyConfirmOrder({
      //   carryWay: delivery,
      //   memberReceiveAddressId: selectAddress ? selectAddress.id : defaultAddress.id,
      //   orderType: 4,
      //   payType: 3,
      //   productId: goodsList[0].id,
      //   productQuantity: 1,
      //   sourceType: 1
      // }).then(res => {
      //   Actions.pay({
      //     order,
      //     price: price,
      //     orderPayType: 'order'
      //   })
      // })

      Actions.pay({
        totalAmount: price + orderShipping.fee,
        fee: orderShipping.fee,
        order,
        price: price,
        orderPayType: 'order'
      })
    } else {
      // 下单
      Actions.pay({
        totalAmount: confirmOrder.calcAmount.totalAmount + orderShipping.fee,
        fee: orderShipping.fee,
        order,
        price: confirmOrder.calcAmount.totalAmount,
        orderPayType: 'order'
      })
    }
  }

  handleDelivery(delivery) {
    const { selectAddress, defaultAddress } = this.props
    let address
    if (defaultAddress) {
      address = defaultAddress
    }
    if (selectAddress) {
      address = selectAddress
    }

    if (address) {
      this.checkOrders({
        disModes: delivery,
        addrId: address.id
      }).then(res => {
        this.setState({
          orderShipping: res.data.data
        })
      })
    }

    this.setState({ delivery })
  }

  render() {
    const { confirmOrder, price, goodsList, submitType } = this.props
    const { delivery, orderShipping } = this.state
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="提交订单"
          back={true}
        />
        <ScrollView
          style={[Style.content, {
            backgroundColor: '#e8e8ed'
          }]}
        >
          {this.renderDefaultAddress()}
          <View style={{
            paddingHorizontal: 15,
            height: 10
          }}>
            {/* <Text style={{ fontSize: 12, color: '#61676F', lineHeight: 32, }}>订单已提交，客服会在1个工作日内对预定订单进行确认</Text> */}
          </View>
          <View style={{
            backgroundColor: '#fff',
            marginBottom: 10,
            borderRadius: 6,
            paddingVertical: 8,

          }}>
            {this.isSubmitType() ?
              goodsList.map((item, index) => {
                return (
                  <View
                    key={index}
                    style={{
                      padding: 15,
                      flexDirection: 'row',
                    }}
                  >
                    <RnImage style={{ width: 50, height: 50 }} uri={item.pic} />
                    <View style={{
                      paddingHorizontal: 10,
                      flex: 1
                    }}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginBottom: 10 }}>{item.name}</Text>
                      <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>RM {item.price}</Text>
                    </View>
                    <View style={{}}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>x{item.quantity}</Text>
                    </View>
                  </View>
                )
              })
              : confirmOrder.cartPromotionItemList.map((item, index) => {
                return (
                  <View
                    key={index}
                    style={{
                      padding: 15,
                      flexDirection: 'row',
                    }}
                  >
                    <RnImage style={{ width: 50, height: 50 }} uri={item.productPic} />
                    <View style={{
                      paddingHorizontal: 10,
                      flex: 1
                    }}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginBottom: 10 }}>{item.productName}</Text>
                      <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>RM {item.price}</Text>
                    </View>
                    <View style={{}}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>x{item.quantity}</Text>
                    </View>
                  </View>
                )
              })}
          </View>
          <View style={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingLeft: 15,
            backgroundColor: '#fff',
            marginBottom: 10,
            borderRadius: 6,
            paddingVertical: 8,
          }}>
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>配送</Text>
            <Picker
              selectedValue={delivery}
              style={{
                height: 50,
                flex: 1,
                color: '#61676F',
              }}
              itemStyle={{ fontSize: size(30), textAlign: 'right' }}
              onValueChange={(delivery) => this.handleDelivery(delivery)}
            >
              <Picker.Item label="自提" value="1" />
              <Picker.Item label="本地特快专递" value="2" />
            </Picker>
          </View>
          {this.renderDelivery()}
          <View style={{
            backgroundColor: '#fff',
            marginBottom: 10,
            borderRadius: 6,
            paddingVertical: 8,
          }}>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>商品数量</Text>
              <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{this.isSubmitType() ? 1 : this.getQuantity()}</Text>
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>商品总价</Text>
              <Text style={{ fontSize: 14, color: '#333', lineHeight: 16, }}>{this.isSubmitType() ? price : confirmOrder.calcAmount.totalAmount}</Text>
            </View>
            {delivery == 2 ? (
              <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 15, paddingVertical: 8 }}>
                <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>特快专递</Text>
                <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>{orderShipping.fee}</Text>
              </View>
            ) : null}
          </View>
        </ScrollView >
        <View style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          paddingLeft: 15,
          borderTopWidth: 1,
          borderTopColor: '#ececee',
        }}>
          <Text style={{}}>
            <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>合计：</Text>
            <Text style={{ fontSize: 14, color: '#f23030', lineHeight: 16, }}>RM {this.isSubmitType() ? price + orderShipping.fee : confirmOrder.calcAmount.totalAmount + orderShipping.fee}</Text>
          </Text>
          <TouchableOpacity
            style={{
              width: 100,
              height: 44,
              backgroundColor: '#f23030',
            }}
            onPress={() => {
              this.handleToPay()
            }}
          >
            <Text style={{ fontSize: 14, color: '#fff', lineHeight: 44, textAlign: 'center' }}>确定</Text>
          </TouchableOpacity>
        </View>
      </View >
    );
  }
}


export default connect(({ confirmOrder, selectAddress, defaultAddress }) => ({
  confirmOrder, selectAddress, defaultAddress
}))(pureRender(SubmitOrders))
